package com.azunitech.apm.bundles.shell;

import java.io.IOException;

import org.osgi.framework.BundleContext;

import com.azunitech.apm.bundles.shell.commands.CommandCONF;
import com.azunitech.apm.bundles.shell.commands.CommandDROP;
import com.azunitech.apm.bundles.shell.commands.CommandDUMP;
import com.azunitech.apm.bundles.shell.commands.CommandEXIT;
import com.azunitech.apm.bundles.shell.commands.CommandINST;
import com.azunitech.apm.bundles.shell.commands.CommandRUOK;
import com.azunitech.apm.bundles.shell.commands.CommandSTOP;
import com.azunitech.apm.bundles.shell.commands.CommandSTRT;



public class FourLetterWords 
{
	private ShellServer<BundleContext> m_ShellServer;
	private int m_Port = 8964;

	public FourLetterWords( BundleContext ctx )
	{
		this(ctx, 8964);
	}
	
	public FourLetterWords( BundleContext ctx, int port )
	{
		m_Port = port;
		m_ShellServer = new ShellServer<BundleContext>(m_Port, 5);
		m_ShellServer.registerTarget(ctx);
		m_ShellServer.registedCommand(new CommandRUOK(), true);
		m_ShellServer.registedCommand(new CommandDUMP(), true);
		m_ShellServer.registedCommand(new CommandSTOP(), true);
		m_ShellServer.registedCommand(new CommandSTRT(), true);
		m_ShellServer.registedCommand(new CommandINST(), true);
		m_ShellServer.registedCommand(new CommandDROP(), true);
		m_ShellServer.registedCommand(new CommandCONF(), true);
		m_ShellServer.registedCommand(new CommandEXIT(), true);
	}
	
	public void startTelnetServer() 
	{
		try 
		{
			this.m_ShellServer.setPort(m_Port);
			m_ShellServer.start();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}

	public void stopTelnetServer() 
	{
		try 
		{
			m_ShellServer.stop();
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
	}
	
	public int getPort() 
	{
		return m_Port;
	}

	public void setPort( int port) 
	{
		this.m_Port = port;
	}

	public String getState() 
	{
		StringBuffer buffer = new StringBuffer();
		buffer.append("ShellServerPort=").append(String.format("%d", m_Port)).append(" ");
		buffer.append("State=").append(m_ShellServer.getState());
		return buffer.toString();
	}

	public String getNewCommands() 
	{
		return this.m_ShellServer.getUnactiveCommands();
	}

	public void activeCommand(String key) 
	{
		this.m_ShellServer.activeCommand(key);
	}
}
